Is it okay to define a [] method in ruby's NilClass?

Posted by Silasj on Programmers See other posts from Programmers or by Silasj
Published on 2012-10-19T19:33:09Z Indexed on 2012/10/19 23:20 UTC
Read the original article Hit count: 104

Filed under:

Ruby by default does not include the method [] for NilClass

For example, to check if foo["bar"] exists when foo may be nil, I have to do:

foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
  # do something with foo["bar"] here
end

If I define this method:

class NilClass
  def [](arg)
    nil
  end
end

Something like that would make this possible, even if foo is nil:

if foo["bar"]
  # do something with foo["bar"]
end

Or even:

if foo["bar"]["baz"]
  # do something with foo["bar"]["baz"] here
end

Question: Is this a good idea or is there some reason ruby doesn't include this functionality by default?

© Programmers or respective owner

Related posts about ruby